<?php
namespace App\Listeners\System\Permission\TreeOrg;

use App\Events\System\Permission\TreeOrg\Updated;
use App\Services\Permission\RoleService;
use App\Services\Permission\PermissionService;

class TreeRoleSyncOrgs
{

    /**
     * 角色(授权树)同步授权平台
     *
     * @param Updated $event
     * @return void
     */
    public function handle(Updated $event)
    {
        if (! count($event->orgIdsDetach) && ! count($event->orgIdsAttach)) {
            return null;
        }

        $roleService = new RoleService();
        $permissionService = new PermissionService();

        // 制作平台权限
        $permissions = $permissionService->orgPermissions($event->orgIdsDetach);
        // 角色删除多平台权限
        $roleService->treeRoleRemovePermissions($event->tree->id, $permissions);

        // 制作平台权限
        $permissions = $permissionService->orgPermissions($event->orgIdsAttach);
        // 角色分配多平台权限
        $roleService->treeRoleAssignPermissions($event->tree->id, $permissions);
    }
}
